package day230420;

import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/4/20 23:29
 * 反转部分单链表
 */
public class Main01 {

    // 节点类
    static class Node {
        int val; // 存储链表的值
        Node next; // 下一节点的位置
        public Node(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            int n = scan.nextInt(); // 单链表节点个数
            // 构造单链表
            // 方便起见, 构造带有头节点的单链表
            Node headNode = new Node(-1);
            Node tail = headNode; // 用于尾插法构造单链表
            while (n-- != 0) {
                int val = scan.nextInt();
                tail.next = new Node(val);
                tail = tail.next;
            }
            // 输入要反转的左右端点区间
            int leftIndex = scan.nextInt();
            int rightIndex = scan.nextInt();
            // 打印链表的值
            Node cur = reversePastList(headNode, leftIndex, rightIndex);
            while (cur != null) {
                if (cur.next != null) {
                    System.out.print(cur.val + " ");
                } else {
                    System.out.print(cur.val);
                }
                cur = cur.next;
            }
            System.out.println();
        }
        scan.close();
    }

    // 反转 leftIndex 与 rightIndex 区间内的链表
    private static Node reversePastList(Node headNode, int leftIndex, int rightIndex) {
        // 先找到需要反转位置起点的节点的前驱节点
        Node pre = headNode;
        for (int i = 1; i < leftIndex; i++) {
            pre = pre.next;
        }
        // 反转操作
        // 需要重复操作 rightIndex - leftIndex 次
        int count = rightIndex - leftIndex;
        Node cur = pre.next;
        while (count-- != 0) {
            Node curNext = cur.next; // 记录当前节点的后一个节点
            cur.next = curNext.next;
            curNext.next = pre.next;
            pre.next = curNext;
        }
        return headNode.next; // 返回头指针(不含头节点)
    }
}
